import gtk


def _get_filename_from_dialog(title, mode):
    dialog = gtk.FileChooserDialog(title,
        None,
        mode,
        (gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL, gtk.STOCK_OPEN, gtk.RESPONSE_OK)
    )
    dialog.set_default_response(gtk.RESPONSE_OK)
    response = dialog.run()
    if response != gtk.RESPONSE_OK:
        fn = None
    else:
        fn = dialog.get_filename()
    dialog.destroy()
    return fn

def get_filename_for_open(title = "Load file"):
    return _get_filename_from_dialog(title, gtk.FILE_CHOOSER_ACTION_OPEN)

def get_filename_for_save(title = "Save file"):
    return _get_filename_from_dialog(title, gtk.FILE_CHOOSER_ACTION_SAVE)

_message_types = dict(
    info = gtk.MESSAGE_INFO,
    warning = gtk.MESSAGE_WARNING,
    question = gtk.MESSAGE_QUESTION,
    error = gtk.MESSAGE_ERROR,
)

def message_box(message, type = "info", buttons = None):
    mtype = _message_types[type]
    if buttons is None:
        if type == "question":
            buttons = gtk.BUTTONS_YES_NO # gtk.BUTTONS_OK_CANCEL
        else:
            buttons = gtk.BUTTONS_OK
    dialog = gtk.MessageDialog(None, flags=0, type=mtype, buttons=buttons, 
        message_format=message)
    res = dialog.run()
    dialog.destroy()
    if res == gtk.RESPONSE_NONE:
        return None
    return res

class InputDialog(gtk.Dialog):
    def __init__(self, message, title):
        gtk.Dialog.__init__(self, message, buttons = (
            gtk.STOCK_OK, gtk.RESPONSE_OK, 
            gtk.STOCK_CANCEL, gtk.RESPONSE_REJECT))
        
        hbox = gtk.HBox()
        lbl = gtk.Label(message)
        hbox.pack_start(lbl, expand = False, fill = False)
        self.text = gtk.Entry()
        self.text.connect("activate", lambda *args: self.response(gtk.RESPONSE_OK))
        self.vbox.pack_start(hbox)
        self.vbox.pack_start(self.text)
        self.vbox.show_all()
    
    def get_text(self):
        return self.text.get_text()

def get_input(message, title = "Input"):
    dialog = InputDialog(message, title)
    res = dialog.run()
    if res == gtk.RESPONSE_OK:
        text = dialog.get_text()
    else:
        text = None
    dialog.destroy()
    return text

def get_form_input(**fields):
    # create a form dialog with the given (field name, default value)
    # return updated **fields
    pass














    